package com.allin.mall.user.controller;

import com.allin.mall.common.core.api.CommonResult;
import com.allin.mall.common.redis.service.RedisService;
import com.allin.mall.user.enums.UserRedisKey;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

@RequestMapping("/api/user/leaderboard")
@RestController
public class UserLeaderboardController {

    @Resource
    private RedisService redisService;

    @GetMapping("/list")
    public CommonResult<Set> list(
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize
            ) {

        return CommonResult.success(redisService.zGetRangeWithScoresDesc(UserRedisKey.LEADERBOARD.getKey(), page, pageSize));
    }

    @GetMapping("/getScore")
    public CommonResult<Number> getScore(
            @RequestParam(value = "value") String value
    ) {

        return CommonResult.success(redisService.zGetScore(UserRedisKey.LEADERBOARD.getKey(), value));
    }

    @PutMapping("/incrementScore")
    public CommonResult<Number> incrementScore(
            @RequestBody Map<String, String> body
    ) {

        return CommonResult.success(redisService.zIncrementScore(UserRedisKey.LEADERBOARD.getKey(), Optional.ofNullable(body.get("value")).orElse("nothing"), Optional.ofNullable(body.get("score")).map(Long::valueOf).orElse(0L)));
    }

    @PostMapping("/add")
    public CommonResult<Boolean> add(@RequestBody Map<String, String> body) {
        redisService.zAdd(
                UserRedisKey.LEADERBOARD.getKey(),
                Optional.ofNullable(body.get("score")).map(Long::valueOf).orElse(0L),
                Optional.ofNullable(body.get("value")).orElse("nothing")
        );
        return CommonResult.success(true);
    }
}
